package recipese.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class GoogleAuthenticationInterceptor extends HandlerInterceptorAdapter {

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
		final UserService userService = UserServiceFactory.getUserService();

        final String thisURL = request.getRequestURI();
        
        final String authUrl;
        final String authText;
        final String greeting;
        
        if (userService.isUserLoggedIn()) {
        	authText = "Logout";
        	authUrl = userService.createLogoutURL(thisURL);
        	greeting = "Hello " + request.getUserPrincipal().getName() + " | ";
        } else {
        	authText = "Login";
        	authUrl = userService.createLoginURL(thisURL);
        	greeting = "";
        }
		
        request.setAttribute("isAdmin", userService.isUserLoggedIn() && userService.isUserAdmin());
        request.setAttribute("user", userService.getCurrentUser());
        request.setAttribute("greeting", greeting);
        request.setAttribute("authUrl", authUrl);
        request.setAttribute("authText", authText);
	}

}
